import copy
import datetime
import json

from django.http import JsonResponse
from django.views import View

from model_app.models import BookInfo


class BookView(View):
    # 带pk 获取一个, 修改一个, 删除一个
    def get(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except Exception as e:
            return JsonResponse({'code': 999, 'msg': 'pk不存在'})
        book_data = {
            'id': book.id,
            'title': book.title,
            'pub_date': book.pub_date,
            'read': book.read,
            'comment': book.comment
        }
        return JsonResponse(book_data)

    def put(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except Exception as e:
            return JsonResponse({'code': 999, 'msg': 'pk不存在'})
        data = json.loads(request.body.decode())
        title = data.get('title', None)
        pub_date = data.get('pub_date', None)
        read = data.get('read', None)
        desc = data.get('desc', None)
        if title:
            book.title = title
        if pub_date:
            book.pub_date = pub_date
        if read:
            book.read = read
        if desc:
            book.desc = desc
        book.save()
        book_data = {
            'id': book.id,
            'title': book.title,
            'pub_date': book.pub_date,
            'read': book.read,
            'comment': book.comment
        }
        return JsonResponse(book_data)

    def delete(self, request, pk):
        try:
            book = BookInfo.objects.get(id=pk)
        except Exception as e:
            return JsonResponse({'code': 999, 'msg': 'pk不存在'})

        book.delete()
        return JsonResponse({}, status=204)


class BookListView(View):
    # 不带pk,  查询, 添加
    def get(self, request):
        query_set = BookInfo.objects.all()

        title = request.GET.get('title', None)
        if title:
            query_set = BookInfo.objects.filter(title=title)

        desc = request.GET.get('desc', None)

        if desc:
            query_set = query_set.filter(desc=desc)

        book_list = []
        for book in query_set:
            book_data = {
                'id': book.id,
                'title': book.title,
                'pub_date': book.pub_date,
                'read': book.read,
                'comment': book.comment
            }
            book_list.append(book_data)

        return JsonResponse(book_list, safe=False)

    def post(self, request):
        # 创建数据
        data = json.loads(request.body.decode())
        title = data.get('title', None)
        pub_date = data.get('pub_date', None)
        read = data.get('read', 0)
        desc = data.get('desc', None)

        # 数据校验的依据?   根据模型的类型
        if all([title, pub_date, desc]):
            pass
        else:
            return JsonResponse({'msg': '参数不足'}, status=400)

        if read.isdigit():
            pass
        else:
            return JsonResponse({'msg': 'read类型不正确'}, status=400)

        try:
            datetime.datetime.strptime(pub_date, '%Y-%m-%d')
        except Exception as e:
            return JsonResponse({'msg': '日期格式有误, 请使用 "YYYY-MM-DD" 格式'}, status=400)

        book = BookInfo(
            title=title,
            pub_date=pub_date,
            read=read,
            desc=desc
        )
        book.save()
        return JsonResponse({
            'id': book.id,
            "title": book.title,
            "desc": book.desc,
            "pub_date": book.pub_date,
            "read": book.read,
        }, status=201)
